﻿using System.Web;
using System.Web.Mvc;
using Sisocana.Core;
using Sisocana.Core.Interfaces;
using Sisocana.Core.Models;


namespace Sisocana.Seguridad
{
    public class SiteAdminAuthorizeAttribute : AuthorizeAttribute
    {
        private ISecurity _security;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated || (httpContext.User.Identity.Name==null))
                return false;
            _security = new Security();

            int idSitio;
            // obtengo el id del sitio a partir del action parameter del controlador
            string id = (httpContext.Request.RequestContext.RouteData.Values["id"] as string)
                     ??
                     (httpContext.Request["id"] as string);
            if (id!=null){
                idSitio = int.Parse(id);
            }else{
                id = (httpContext.Request.RequestContext.RouteData.Values["idsitio"] as string)
                     ??
                     (httpContext.Request["idsitio"] as string);
                idSitio = int.Parse(id);

            }
            

            //verifico que el usuario tenga permiso para configurar el sitio
            return ( (_security.HasPermissionGralAdmin (httpContext.User.Identity.Name)) 
                || (_security.HasPermissionSiteAdmin (httpContext.User.Identity.Name , idSitio)) );
        }
    }
}